#ifndef _Buffer_
#define _Buffer_

#include "util.hpp"
#include "vector"
#include <cassert>
namespace log{

    #define DEFAULT_BUFFER_SIZE  (10*1024*1024)
    #define THRESHOLD_BUFFER_SIZE (80*1024*1024)//阀值
    #define INCREMENT_BUFFER_SIZE (10*1024*1024)//线性增长
    class Buffer{
        public:
        Buffer()
        :_buffer(DEFAULT_BUFFER_SIZE)
        ,_reader_idx(0)//读到文件
        ,_writer_idx(0)//写进内存
        {}

        void push(const char *data, size_t len)
        {
            //缓冲去不够的情况下， 1.扩容
            //1.固定的大小版本，则直接返回
           // if(_buffer.size() + len > DEFAULT_BUFFER_SIZE){return;}
            //2.动态扩容版本, 用于极限性能测试

            ensureEnoughSize(len);//考虑空间不够则扩容
            std::copy(data, data+len, &_buffer[_writer_idx]);//将数据拷贝到缓冲区
            moveWrite(len);//将当前写入位置向后偏移
         
        }

        const char* begin()
        {
            return &_buffer[_reader_idx];
        }
        
        //返回可以读取的长度
        size_t readAbleSize()
        {
            return _writer_idx - _reader_idx;
        }

        size_t writeAbleSize()
        {
            return _buffer.size() - _writer_idx;
        }

        //读取指针走len个长度
        void moveReader(size_t len)
        {
            assert(len <= readAbleSize());
            _reader_idx += len;
        }
        
        void moveWrite(size_t len)
        {
            assert(len <= writeAbleSize());
            _writer_idx += len;
        }

        //重置读写位置，初始化缓冲区
        void reset()
        {
           // _buffer.clear();
            _writer_idx = 0;
            _reader_idx = 0;
        }
        //对buffer进行交换工作
        void swap(Buffer &buffer)
        {
            _buffer.swap(buffer._buffer);
           std:: swap(_reader_idx, buffer._reader_idx);
           std:: swap(_writer_idx, buffer._writer_idx);
        } 
        
        //判断缓冲区是否为空
        bool empty()
        {
            return(_reader_idx == _writer_idx);
        }
        private:
        void ensureEnoughSize(size_t len)
        {
            if(len < writeAbleSize()) return;//不需要扩容
            
            size_t newsize = 0;
            if(_buffer.size() < THRESHOLD_BUFFER_SIZE)
            {
                newsize = _buffer.size() * 2; //小于阀值成倍增长
            }  
            else
            {
                newsize = _buffer.size() + INCREMENT_BUFFER_SIZE;//否则线性增长
            }
                _buffer.resize(newsize);
        }

        private:
        std::vector<char> _buffer;
        size_t _reader_idx;
        size_t _writer_idx;

    };


}


#endif